package com.hq.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hq.bean.User;
import com.hq.service.UserService;
import com.hq.util.FileUploadUtils;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("list.do")
    public String list(Model model){
        PageHelper.startPage(1,10);
        List list=userService.list();
        PageInfo<User> info = new PageInfo<>();

        model.addAttribute("list",list);
        model.addAttribute("pi",info);
        return "list";
    }

    @RequestMapping("toadd.do")
    public String toadd(){
        return "add";
    }

    @RequestMapping("add.do")
    public String add(MultipartFile file, User user, HttpSession session){
        if(file.getOriginalFilename().length()>0){
            String upload = FileUploadUtils.load(session, file, "upload");
            user.setPic(upload);
        }
        userService.addUser(user);
        return "redirect:list.do";
    }

    @RequestMapping("down.do")
    public String down(String fileName, HttpServletRequest request, HttpServletResponse response){
        FileUploadUtils.down(fileName,"upload",response,request);
        return null;
    }
    @RequestMapping("del.do")
    @ResponseBody
    public Object del(Integer id){
        int i = userService.delUser(id);
        return i;
    }

}
